package com.chargerlink.echarger.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chargerlink.echarger.pojo.Charger;
import com.chargerlink.echarger.pojo.Station;
import com.chargerlink.echarger.until.KeysUntil;
import com.chargerlink.echarger.until.TaskRedisTemplate;
import com.chargerlink.echarger.vo.request.StationVO;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * Created by fansxnet on 17-5-5.
 */

/**
 * cluster.geoadd(key, point.getX(), point.getY(), member);
 * <br>
 * GEOADD key longitude latitude member [longitude latitude member ...]
 * <br>
 * public Point(double x, double y)
 * <p>
 * 经度：longitude
 * 纬度：latitude
 * 纬度为 南纬90-0-北纬90
 * 经度为 西经180-本出子午线(0度)-东经180
 */
@Service
public class PoiService {

    Logger logger = Logger.getLogger(this.getClass());

    @Value("${loadStationsUrl}")
    private String loadStationsUrl;


    @Autowired
    TaskRedisTemplate taskRedisTemplate;

    @PostConstruct
    public void init() {
//        taskRedisTemplate.delete(key);
    }

    public void addStation(Station station) {
        taskRedisTemplate.boundValueOps(KeysUntil.stationsKey(station.getId())).set(station);
        taskRedisTemplate.opsForGeo().geoAdd(KeysUntil.GEO_QUEUE, new Point(station.getLng(), station.getLat()), KeysUntil.stationsKey(station.getId()));
    }


    /**
     * 纬度为 南纬90-0-北纬90
     * 经度为 西经180-本出子午线(0度)-东经180
     */
    public void set() {
        Point p = new Point(3, 4);
        String id = "ID:" + System.currentTimeMillis();
        taskRedisTemplate.opsForGeo().geoAdd(KeysUntil.GEO_QUEUE, p, id);
        System.out.println(System.currentTimeMillis());
    }


    public void get() {

        Point p = new Point(3, 4);
        String id = "ID:" + System.currentTimeMillis();
        Point center = new Point(3, 4);
        Distance dist = new Distance(2000, Metrics.NEUTRAL);

        Circle within = new Circle(center, dist);
        GeoResults<RedisGeoCommands.GeoLocation<Object>> geos = taskRedisTemplate.opsForGeo().geoRadius(KeysUntil.GEO_QUEUE, within);
        if (geos == null) return;

        Iterator<GeoResult<RedisGeoCommands.GeoLocation<Object>>> it = geos.iterator();
        while (it.hasNext()) {
            System.out.println(it.next().getContent().getName());
        }

    }




    public List<Object> query(Double lng, Double lat, Double radius, Double radiusMax, Integer desireCount) {
        GeoOperations<String, Object> opsGeo = taskRedisTemplate.opsForGeo();

        Point center = new Point(lng, lat);
        Distance dist = new Distance(radius, Metrics.NEUTRAL);
        Circle within = new Circle(center, dist);
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs();

        args.sortAscending();
        GeoResults<RedisGeoCommands.GeoLocation<Object>> geos = opsGeo.geoRadius(KeysUntil.GEO_QUEUE, within, args);

        if (geos == null || geos.getContent().size() < desireCount) {//扩大搜索范围
            dist = new Distance(radiusMax, Metrics.NEUTRAL);
            within = new Circle(center, dist);
            geos = opsGeo.geoRadius(KeysUntil.GEO_QUEUE, within, args);
            if (geos == null) return new ArrayList<Object>();
        }

        List<String> stationKeys = new ArrayList<String>();
        Iterator<GeoResult<RedisGeoCommands.GeoLocation<Object>>> it = geos.iterator();

        while (it.hasNext()) {
            stationKeys.add((String) it.next().getContent().getName());
        }

        return taskRedisTemplate.opsForValue().multiGet(stationKeys);
    }

    public Station getStation(Integer id) {
        return (Station) taskRedisTemplate.opsForValue().get(KeysUntil.stationsKey(id.toString()));
    }


    public void loadData() throws IOException {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(loadStationsUrl)
                .build();

        Response response = client.newCall(request).execute();
        JSONObject parser = JSON.parseObject(response.body().string());
        if (parser.getIntValue("result") == 1) {
            JSONArray stations = parser.getJSONArray("data");
            for (int i=0;i<stations.size();i++){
                Station station = JSON.parseObject(stations.getJSONObject(i).toJSONString(),Station.class);
                addStation(station);
            }
        }else {
            logger.error(parser.getString("message"));
        }

    }

    public List<Charger> getParklist(Integer id) {
        return null;
    }


    public Void chargerCorrect(StationVO stationVO) {
        return null;
    }




    public List<Object> search(String keyword, Double lng, Double lat, Integer offset, Integer limit) {
        if(lng==null || lat==null ) {

        }else {

        }
        return null;
    }

    public Void stakeRepair(String stationId, String stakeNo, String repairType) {
        return null;
    }

    public Void config() {
        return null;
    }
}
